package com.glela.controller;

import java.util.Date;
import java.util.List;

import com.glela.cache.model.RedisKey;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.JsonUtil;
import com.glela.goods.model.StoreGoods;
import com.glela.goods.model.request.StoreGoodsRequest;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.service.StoreGoodsService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;

/**
 * 
* @ClassName: StoreGoodsController
* @Description: 【店主精选商品】业务入口
* @author NingChongQing
* @date 2017年7月7日 上午9:36:24
 */
@Controller
@RequestMapping(value = "storeGoods", produces = "application/json;charset=UTF-8")
public class StoreGoodsController extends BaseController {

	private static org.slf4j.Logger logger			= LoggerFactory.getLogger(StoreGoodsController.class);

	@Autowired
	private StoreGoodsService storeGoodsService;
	@Autowired
	private UserService userService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	/**
	 * 
	* **********************************************
	* @Title: getStoreGoodsList
	* @Description: 查找店主精选商品列表
	* @param @param request
	* @param @return    设定文件
	* @return ResponseEntity<?>    返回类型
	* @throws		异常
	* @author NingChongQing		作者
	* @date 2017年7月8日 下午2:54:12		时间
	* **********************************************
	 */
	
//	
//	@RequestMapping(value = "/getStoreGoodsList", method = RequestMethod.POST, consumes = "application/json")
//	@ResponseBody
//	public ResponseEntity<?> getStoreGoodsList(@RequestBody StoreGoodsRequest request)
//	{
//		try {
//			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
//			}
//			//店主用户ID  默认校妆姐姐店铺的店主ID
//			Integer storeUserId = Integer.valueOf(BaseConstants.XZ_SISTER+"");
//			// 显示当前登录或者分享人的店铺信息
//			Long showUserId = 0L;
//			if (!ParameterUtils.validParams(request.getTalentId())) {// 分享人
//				showUserId = Long.valueOf(request.getTalentId());
//			} else if (!ParameterUtils.validParams(request.getUserId())) {// 当前登录人
//				showUserId = request.getUserId();
//			}
//			// 没有绑定店主且不是从分享链接查看店主精选商品列表
//			if (showUserId.intValue() != 0) {
//				User user = this.userService.getUserById(showUserId);
//				User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
//				storeUserId = storeUser.getId().intValue();
//			}
//			Integer topBannerId = 1;
//			if (!ParameterUtils.validParams(request.getTopBannerId())) {
//				topBannerId = request.getTopBannerId();
//			}
//			String from = "";
//			if (!ParameterUtils.validParams(request.getFroms())) {
//				from = request.getFroms();
//			}
//			Integer startIndex = request.getStartIndex();
//			Integer pageSize = 10; // 默认为10，方便店主精选商品上下架时清楚缓存
//			String tempKey = "temp:com:glela:controller:StoreGoodsController:getStoreGoodsList:" + storeUserId + "-1";
////			Long dataSize= redisUtil.llength(tempKey);
//            pageSize = startIndex+pageSize-1;
//            List<String> redislist = redisUtil.lrange(tempKey, 0, -1);
//			StoreGoods storeGoods = new StoreGoods();
//			storeGoods.setStoreUserId(storeUserId);
//			logger.info("=======================storeuid:"+storeUserId+"================================");
//			long mainStart = System.currentTimeMillis();
//			String storeCount = redisUtil.get(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeUserId);//storeGoodsService.selectCount(storeGoods);
//			/*if (StringUtils.isBlank(storeCount)){
//				storeCount = storeGoodsService.selectCount(storeGoods)+"";
//				redisUtil.set(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeUserId,Integer.valueOf(storeCount));
//			}*/
//			/*int count = Integer.valueOf(storeCount);
//			if (dataSize.intValue()!=count) {
//				//如果数据库跟缓存数据不一致清除缓存重新同步
//				redisUtil.del(tempKey);
//				redisUtil.del(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeUserId);
//				dataSize = 0L;
//			}*/
//			if ((CollectionUtils.isEmpty(redislist))) {
//				logger.info("=============if==========storeuidstart:"+storeUserId+"================================开始查询数据库列表");
//				long startTime = System.currentTimeMillis();
//				List<GoodsListResponse> list = this.storeGoodsService.findStoreGoodsListByPage(storeUserId,topBannerId,from,0,pageSize);
//				logger.info("=============if==========storeuidend:"+storeUserId+"================================查询数据库列表结束耗时："+(System.currentTimeMillis()-startTime));
//				String[] toBeStored = new String[list.size()];
//                List<GoodsListResponse> results = new ArrayList<GoodsListResponse>();
//				for (int i = 0; i <list.size() ; i++) {
//					toBeStored[i]=JsonUtil.toJson(list.get(i));
//                    results.add(list.get(i));
//				}
//				redisUtil.rpush(tempKey,toBeStored);
////				redisUtil.set(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeUserId,Integer.valueOf(list.size()));
////				redisUtil.expire(tempKey+"-time", 900);
////				pageSize = startIndex+pageSize-1;
//                redisUtil.set(tempKey+"-expire","1",600);
//				/**
//				 * 180118改为不分页
//				 */
//				logger.info("=============if==========storeuidend:"+storeUserId+"================================方法总耗时："+(System.currentTimeMillis()-mainStart));
//                if (StringUtils.isBlank(storeCount)){
//                    redisUtil.set(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeUserId,list.size());
//                }
//				return toRespEntity(toResultModelJSON(new ResponsePageModel<GoodsListResponse>(results.size(), request.getPageSize(), request.getPageNum(), results)));
//			} else {
//				/*pageSize = startIndex+pageSize-1;
//				List<String> list = redisUtil.lrange(tempKey, 0, -1);
//				if (list.size()==0) {
//					*//**
//					 * 防止查询list长度时有值但是取缓存时key刚好失效导致取不到数据的问题
//					 *//*
//					logger.info("========else===============storeuidstart:"+storeUserId+"================================开始查询数据库列表");
//					long startTime = System.currentTimeMillis();
//					List<GoodsListResponse> queryResultList = this.storeGoodsService.findStoreGoodsListByPage(storeUserId,topBannerId,from,0,count);
//					logger.info("========else===============storeuidend:"+storeUserId+"================================查询数据库列表结束耗时："+(System.currentTimeMillis()-startTime));
//					*//*for (GoodsListResponse goodsListResponse : queryResultList) {
//						redisUtil.rpush(tempKey, JsonUtil.toJson(goodsListResponse));
//					}*//*
//					String[] toBeStored = new String[list.size()];
//					for (int i = 0; i <queryResultList.size() ; i++) {
//						toBeStored[i]=JsonUtil.toJson(queryResultList.get(i));
//					}
//					redisUtil.rpush(tempKey,toBeStored);
//					list = redisUtil.lrange(tempKey, startIndex, pageSize);
//				}*/
//                if (StringUtils.isBlank(redisUtil.get(tempKey+"-expire"))){
//                    storeGoodsService.reloadStoreList(storeUserId,topBannerId,from,0,redislist.size());
//                    redisUtil.set(tempKey+"-expire","1",600);
//                }
//				List<GoodsListResponse> results = new ArrayList<GoodsListResponse>();
//				for (String grStr : redislist) {
//					GoodsListResponse goodsListResponse = JSON.parseObject(grStr,GoodsListResponse.class);
//					results.add(goodsListResponse);
//				}
//				logger.info("=============else==========storeuidend:"+storeUserId+"================================方法总耗时："+(System.currentTimeMillis()-mainStart));
//                if (StringUtils.isBlank(storeCount)){
//                    redisUtil.set(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeUserId,redislist.size());
//                }
//				return toRespEntity(toResultModelJSON(new ResponsePageModel<GoodsListResponse>(results.size(), request.getPageSize(), request.getPageNum(), results)));
//			}
//		} catch (Exception e) {
//			getLOGGER().error("查询买家店主精选商品异常:{}", e.getMessage(), e);
//			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
//		}
//	}
	
	
	
	@RequestMapping(value = "/getStoreGoodsList", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> getStoreGoodsList(@RequestBody StoreGoodsRequest request)
	{
		try {
			
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//店主用户ID  默认校妆姐姐店铺的店主ID
			Integer storeUserId = Integer.valueOf(BaseConstants.XZ_SISTER+"");
			//显示当前登录或者分享人的店铺信息
			Long showUserId = 0L;
			if (!ParameterUtils.validParams(request.getTalentId())) { //分享人
				showUserId = Long.valueOf(request.getTalentId());
			} else if (!ParameterUtils.validParams(request.getUserId())) { //当前登录人
				showUserId = request.getUserId();
			}
			//没有绑定店主且不是从分享链接查看店主精选商品列表
			if (showUserId.intValue() != 0) {
				User user = this.userService.getUserById(showUserId);
				User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
				storeUserId = storeUser.getId().intValue();
			}
			Integer topBannerId = 1;
			if (!ParameterUtils.validParams(request.getTopBannerId())) {
				topBannerId = request.getTopBannerId();
			}
			String from = "";
			if (!ParameterUtils.validParams(request.getFroms())) {
				from = request.getFroms();
			}
			Integer startIndex = request.getStartIndex() == 0 ? 1 : request.getStartIndex();
			Integer pageSize = 10;
			//缓存店主上架商品的REDIS LIST KEY
			String tempKey = "temp:com:glela:controller:StoreGoodsController:getStoreGoodsList:" + storeUserId + "-1";
			String tempKey_expire = tempKey + "-expire";
			//
			int startRow = request.getStartIndex();
			int endRow   = startRow+10 - 1;
			
			Long dataSize= redisUtil.llength(tempKey);
			if(dataSize != null && dataSize > 0) {//数据已缓存
				String expire_value = redisUtil.get(tempKey_expire);
				if(StringUtils.isBlank(expire_value)) {
					//更新该用户上架产品列表到REDIS
					storeGoodsService.reloadStoreList(tempKey,storeUserId,topBannerId,from,0,CommonConstants.STORE_GOODS_NUM_MAX);
				}
				List<GoodsListResponse> results = this.storeGoodsService.readerRedisStoreGoods(startRow,endRow,tempKey);
				return toRespEntity(toResultModelJSON(new ResponsePageModel<GoodsListResponse>(dataSize.intValue(), request.getPageSize(), request.getPageNum(), results)));
				
			}else {
				List<GoodsListResponse> list = this.storeGoodsService.findStoreGoodsListByPage(storeUserId,topBannerId,from,0,pageSize);
				String[] toBeStored = new String[list.size()];
				for (int i = 0; i <list.size() ; i++) {
					toBeStored[i]=JsonUtil.toJson(list.get(i));
				}
				if(toBeStored != null && toBeStored.length > 0) {
					redisUtil.rpush(tempKey,toBeStored);
					redisUtil.set(tempKey_expire, "1", 360);
				}				
				List<GoodsListResponse> results = this.storeGoodsService.readerRedisStoreGoods(startRow,endRow,tempKey);
				return toRespEntity(toResultModelJSON(new ResponsePageModel<GoodsListResponse>(list.size(), request.getPageSize(), request.getPageNum(), results)));
			}	
		}catch(Exception e) {
			getLOGGER().error("查询买家店主精选商品异常:{}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}			
	}
	

	
	
	
	
	
	/**
	 * 
	* **********************************************
	* @Title: insertStoreGoods
	* @Description: 上架店主精选商品
	* @param @param request
	* @param @return    设定文件
	* @return ResponseEntity<?>    返回类型
	* @throws		异常
	* @author NingChongQing		作者
	* @date 2017年7月8日 下午3:09:41		时间
	* **********************************************
	 */
	@RequestMapping(value = "/upperStoreGoods", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> upperStoreGoods(@RequestBody StoreGoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(request.getGoodsId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			User user = this.userService.getUserById(request.getUserId());
			User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
			Integer storeUserId = storeUser.getId().intValue();
			StoreGoods storeGoods = new StoreGoods();
			storeGoods.setStoreUserId(storeUserId);
			storeGoods.setTopBannerId(1);
			storeGoods.setGoodsId(request.getGoodsId());
			storeGoods.setCrteator(storeUserId);
			storeGoods.setCreateTime(new Date());
			return this.storeGoodsService.addStoreGoods(storeGoods);
		} catch (Exception e) {
			getLOGGER().error("店主精选商品上架失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 
	* **********************************************
	* @Title: modifyStoreGoods
	* @Description: 下架店主精选商品
	* @param @param request
	* @param @return    设定文件
	* @return ResponseEntity<?>    返回类型
	* @throws		异常
	* @author NingChongQing		作者
	* @date 2017年7月8日 下午3:11:46		时间
	* **********************************************
	 */
	@RequestMapping(value = "/offStoreGoods", method = RequestMethod.POST, consumes = "application/json")
	@ResponseBody
	public ResponseEntity<?> offStoreGoods(@RequestBody StoreGoodsRequest request) {
		try {
			if (ParameterUtils.validParams(request.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(request.getGoodsId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			User user = this.userService.getUserById(request.getUserId());
			User storeUser =this.userService.getUserByPersionId(user.getRecommendFrom());
			Integer storeUserId = storeUser.getId().intValue();
			StoreGoods storeGoods = new StoreGoods();
			storeGoods.setStoreUserId(storeUserId);
			storeGoods.setTopBannerId(1);
			storeGoods.setGoodsId(request.getGoodsId());
			String storeCount = redisUtil.get(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+request.getUserId());//storeGoodsService.selectCount(storeGoods);
			if (StringUtils.isBlank(storeCount)){
				storeCount = storeGoodsService.selectCount(storeGoods)+"";
				redisUtil.set(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+request.getUserId(),Integer.valueOf(storeCount));
			}
			redisUtil.decr(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+request.getUserId());
			return this.storeGoodsService.removeStoreGoods(storeGoods);
		} catch (Exception e) {
			getLOGGER().error("店主精选商品下架失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
/*
	@RequestMapping("/testredis")
	public String testRedis(){
		String key = "adfadsfasdfsa";
		List<String> list = new ArrayList<>();
		Long signStart = System.currentTimeMillis();
		for (int i = 0; i < 1000; i++) {
			redisUtil.rpush(key,""+i);
		}
		System.out.println("单个添加耗时："+(System.currentTimeMillis()-signStart)+"=====================================");
		for (int i = 0; i < 1000; i++) {
			list.add(i+"");
		}
		Long batchStart = System.currentTimeMillis();
		String[] store = new String[list.size()];
		list.toArray(store);
		redisUtil.rpush("kkkkkkkk",store);
		System.out.println("批量添加耗时："+(System.currentTimeMillis()-batchStart)+"============================================");
		return "";
	}*/

}
